package com.scproject.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LNL
 * @date 2021/4/25 13:54
 */
public class JWTUtils {
    private static final String SIGN = "@*CDUEST^HK%WJ";

    /**
     * 生成Token
     * @param map
     * @return
     */
    public static String generateToken(Map<String,String> map) {
        //创建JWT对象
        JWTCreator.Builder builder = JWT.create();

        //将负载信息存入token中
        map.forEach((k,v) -> builder.withClaim(k,v));

        //过期时间，设置为一周
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,7);

        String token = builder
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    /**
     * 验证token
     * @param token
     */
    public static void verifyJWT (String token) {
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取用户的id和username的map集合
     * @param token
     * @return
     */
    public static Map<String,String> getInfo(String token) {
        Map<String,String> userMap = new HashMap<>();
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        Map<String, Claim> map = verify.getClaims();
        map.forEach((k,v) -> userMap.put(k,v.asString()));
        return userMap;
    }


}
